# -*- coding: utf-8 -*-
# @Function: 主控制程序
# @Description: 系统主控制文件，调用各个模块完成Excel导入和查询测试，是整个流程的入口点
# @Usage: 直接运行此文件可执行完整的数据导入和查询测试流程
# @Dependencies: importer.py, query_tester.py

import os
import sys
from pathlib import Path

from Z_importer import QAImporter
from Z_query_tester import QueryTester

def get_qa_final_path():
    """获取QA_final文件夹路径"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(current_dir)
    qa_final_path = os.path.join(project_root, "C_filter", "QA_final")
    return qa_final_path

def get_csv_path():
    """获取CSV文件路径"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(current_dir)
    csv_path = os.path.join(project_root, "A_segmenter", "csv", "大伙房水库调度规程.csv")
    return csv_path

def import_data():
    """导入Excel数据"""
    qa_final_path = get_qa_final_path()
    print(f"QA_final目录: {qa_final_path}")
    
    importer = QAImporter()
    success_count, total_count = importer.process_folder(qa_final_path)
    
    print(f"\nExcel导入结果: {success_count}/{total_count} 个文件成功导入")
    return success_count > 0

def import_csv_tables():
    """导入CSV表格数据"""
    csv_file_path = get_csv_path()
    print(f"\nCSV文件路径: {csv_file_path}")
    
    if not os.path.exists(csv_file_path):
        print("CSV文件不存在，跳过CSV表格导入")
        return False
    
    importer = QAImporter()
    try:
        # 使用已实现的process_specific_csv方法
        success = importer.process_specific_csv(csv_file_path)
        if success:
            print("CSV表格导入成功")
        else:
            print("CSV表格导入失败")
        return success
    except Exception as e:
        print(f"CSV表格导入失败: {e}")
        return False

def test_queries():
    """测试查询"""
    test_questions = [
        "1995典型年的洪峰是多少？"
    ]
    
    tester = QueryTester()
    for test_question in test_questions:
        print("\n" + "=" * 50)
        tester.test_query(test_question)

def main():
    """主函数"""
    print("=== Excel QA数据导入工具 ===")
    
    try:
        # 步骤1: 导入Excel数据
        excel_success = import_data()
        
        # 步骤2: 导入CSV表格数据
        csv_success = import_csv_tables()
        
        # 步骤3: 测试查询
        if excel_success or csv_success:
            test_queries()
        else:
            print("\n由于导入失败，跳过查询测试")
        
    except Exception as e:
        print(f"\n程序执行失败: {e}")

if __name__ == "__main__":
    main()